/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.vng.zing.survey.controller;

import com.vng.zing.survey.thrift.client.SurveyClient;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.vng.zing.survey.model.CommonModel;
import com.vng.zing.survey.thrift.model.Error;
import com.vng.zing.survey.thrift.model.SurveyItemResult;
import com.vng.zing.survey.thrift.model.UserType;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import java.util.Map;
import org.apache.log4j.Logger;

/**
 *
 * @author namhh
 */
public class AjaxDeleteResponse extends BaseController {
private static  UserType userType = UserType.ADMIN;
    @Override
    public String render(HttpServletRequest request, HttpServletResponse resp) throws IOException, Exception {
        try {
            if (request.getParameter("idSurvey") == null || request.getParameter("arrID") == null) {
                return CommonModel.toJSON("ERROR", "Tham số không hợp lệ!");
            }
            int idSurvey = Integer.parseInt(request.getParameter("idSurvey"));
            String myJsonData = request.getParameter("arrID");
            String[] arrID = myJsonData.split(",");
            if (arrID.length <= 0) {
                return CommonModel.toJSON("ERROR", "Không có gì để xóa!");
            }
            
           Map map = checkMember(request, userType);
            if(map.containsValue(ErrorType.FAIL)||map.containsValue(ErrorType.ERROR_SYSTEM))
                return CommonModel.toJSON("ERROR", (String)map.get("msg"));
            int idUser= (int)map.get("msg");
            SurveyItemResult surveyItemResult = SurveyClient.getInstance().getSurvey(idSurvey);
            if(idUser!=surveyItemResult.getSurveyItem().getIDUser()){
                return CommonModel.toJSON("ERROR", "Bạn không phải là admin!");
            } 
            JSONObject jSONObject = new JSONObject();
            jSONObject.put("idSurvey", idSurvey);
            JSONArray array = new JSONArray();
            SurveyClient surveyClient = SurveyClient.getInstance();
            for (String string : arrID) {
                int id = Integer.parseInt(string);
                if (surveyClient.removeResponse(idSurvey, id) == Error.SUCCESS) {
                    array.add(id);
                }
            }
            jSONObject.put("idUser", array);
            return jSONObject.toJSONString();
        } catch (Exception ex) {
            Logger.getLogger(this.getName()).error(ex.toString());
            return CommonModel.toJSON("ERROR", "");
        }

    }
}
